package com.spring.statemachine.template;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mayixiang
 * @date 2021-02-18 19:18
 */
public class TestTemplate {

    String json = "{\"process\":{\"task\":[{\"id\":\"start\",\"name\":\"开始\",\"handlerClass\":\"\",\"returnEnum\":[],\"type\":\"START\",\"target\":[{\"returnEnum\":\"SUCCESS\",\"targetRef\":\"evalCheck\"}]},{\"id\":\"start\",\"name\":\"估值核对\",\"handlerClass\":\"\",\"returnEnum\":[\"SUCCESS\",\"DIFFERENCE\"],\"target\":[{\"returnEnum\":\"SUCCESS\",\"targetRef\":\"end\"},{\"returnEnum\":\"DIFFERENCE\",\"targetRef\":\"adjustEvaluate\"}],\"type\":\"WORK\"},{\"id\":\"adjustEvaluate\",\"name\":\"调平后估值\",\"handlerClass\":\"\",\"returnEnum\":[\"SUCCESS\"],\"target\":[{\"returnEnum\":\"SUCCESS\",\"targetRef\":\"evalCheck2\"}],\"type\":\"WORK\"},{\"id\":\"evalCheck2\",\"name\":\"估值核对2\",\"handlerClass\":\"\",\"returnEnum\":[\"SUCCESS\"],\"target\":{\"returnEnum\":\"SUCCESS\",\"targetRef\":\"end\"},\"type\":\"WORK\"},{\"id\":\"end\",\"name\":\"结束\",\"handlerClass\":\"\",\"returnEnum\":[],\"checkScene\":[{\"targetRef\":\"evalCheck\",\"returnEnum\":\"SUCCESS\"},{\"targetRef\":\"rpt\",\"returnEnum\":\"SUCCESS\"}],\"type\":\"END\"}]}}";

    public void aa() throws Exception {
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject process = jsonObject.getJSONObject("process");
        List<ProcessTask>
            task =
            JSONArray.parseArray(process.getJSONArray("task").toJSONString(), ProcessTask.class);
        Map<String, ProcessTask> processTaskMap = new HashMap<>();
        for (ProcessTask processTask : task) {
            if (processTaskMap.get(processTask.getId()) != null){
                throw new Exception("重复了兄弟 processId:"+processTask.getId());
            }
            processTaskMap.put(processTask.getId(), processTask);
        }
        getProcessTask(processTaskMap, "start");
    }

    public void getProcessTask(Map<String, ProcessTask> processTaskMap, String id){
        ProcessTask processTask = processTaskMap.get(id);
        System.out.println(JSON.toJSONString(processTask));
        if (!CollectionUtils.isEmpty(processTask.getTarget())){
            List<Target> targetList = processTask.getTarget();
            for (Target target : targetList) {
                getProcessTask(processTaskMap, target.getTargetRef());
            }
        }
    }
}
